//
//  CZRefreshControl.swift
//  Blog
//
//  Created by whitcast on 16/7/16.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
// 控件的高度
private let CZRefreshControlHeight: CGFloat = 50

enum CZRefreshControlState: Int {
    // 下拉刷新状态
    case Normal = 0
    // 松手就刷新
    case Pulling = 1
    // 正在刷新
    case Refreshing = 2
}
// 自定义下拉刷新控件
class CZRefreshControl: UIControl {
    // 当前下拉刷新的状态
    private var refreshState: CZRefreshControlState = .Normal {
        didSet {
            switch refreshState {
            case.Normal:
                print("下拉刷新")
                 //  1. 内容设置为下拉刷新,箭头重置
                messageLabel.text = "下拉刷新"
                // 显示箭头，关闭风火轮
                iconImageView.hidden = false
                // 停止风火轮就会隐藏这个视图
                indicatorView.stopAnimating()
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.iconImageView.transform = CGAffineTransformIdentity
                })
                //  oldValue是上一次存储值
                if oldValue == .Refreshing {
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.currentScrollView?.contentInset.top -= CZRefreshControlHeight
                    })
                }
            case .Pulling:
                print("松手就刷新")
                //  1.内容设置松手就刷新, 箭头调转
                messageLabel.text = "松手就刷新"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.iconImageView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case .Refreshing:
                print("正在刷新")
                 //  1.内容设置正在刷新, 箭头隐藏, 开启风火轮
                messageLabel.text = "正在刷新。。。。。"
                iconImageView.hidden = true
                indicatorView.startAnimating()
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.currentScrollView?.contentInset.top += CZRefreshControlHeight
                })
                 //  通知外界进行加载数据, 发送事件
                sendActionsForControlEvents(.ValueChanged)
            }
        }
    }
    // 当前滚动视图
    private var currentScrollView: UIScrollView?
    // MARK: -- 懒加载
    // 下拉箭头
    private lazy var iconImageView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    // 内容Label
    private lazy var messageLabel:UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(12)
        label.textColor = UIColor.grayColor()
        label.text = "下拉刷新"
        return label
    }()
    // 风火轮
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // 添加控件设置约束
    private func setupUI() {
       
        backgroundColor = UIColor.orangeColor()
        // 添加控件，设置约束
        addSubview(iconImageView)
        addSubview(messageLabel)
        addSubview(indicatorView)
        // 使用系统约束进行布局
        iconImageView.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
        
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .Leading, relatedBy: .Equal, toItem: iconImageView, attribute: .Trailing, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .CenterY, relatedBy: .Equal, toItem: iconImageView, attribute: .CenterY, multiplier: 1, constant: 0))
        
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .CenterY, relatedBy: .Equal, toItem: iconImageView, attribute: .CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .CenterY, relatedBy: .Equal, toItem: iconImageView, attribute: .CenterY, multiplier: 1, constant: 0))
        indicatorView.startAnimating()
        
    }
    // 将要添加到哪个父控件的时候去调用
    override func willMoveToSuperview(newSuperview: UIView?) {
        // 判断器父控件能否滚动
        guard let scrollView = newSuperview as?     UIScrollView else {
            return
        }
        //  代码执行到此视图一定能够滚动
        //  设置自己的frame
        self.frame.size = CGSize(width: scrollView.frame.size.width, height: CZRefreshControlHeight)
        self.frame.origin.y = -CZRefreshControlHeight
        // 使用kvo监听其父控件的滚动
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
        currentScrollView = scrollView
    }
    // kvo监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        guard let scrollView = currentScrollView else {
            return
        }
        //  业务逻辑处理
        //  1. 如果拖动情况下, 有两种状态 1. 下拉刷新状态 2. 松手就刷新的状态

        //  2. 如果松手情况下, 就要进入'正在刷新的状态' 前提(当前的刷新状态 松手就刷新的状态)
        if scrollView.dragging{
            //  因为负数  我们进对临界点-114进行判断,如果是小于-114表示进入的一个松手就刷新的状态
            if scrollView.contentOffset.y < -(scrollView.contentInset.top + CZRefreshControlHeight) && refreshState == .Normal{
                print("松手就刷新")
                refreshState = .Pulling
            }else if scrollView.contentOffset.y >=  -(scrollView.contentInset.top + CZRefreshControlHeight) && refreshState == .Pulling{
                print("下拉刷新")
                refreshState = .Normal
            }
        }else {
            if refreshState == .Pulling{
                refreshState = .Refreshing
                print("正在刷新")
            }
        }
    }
    deinit {
        // 移除kvo
        currentScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
}
